package suites.stub {
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	import org.splink.deepsplink.page.IPageSupplier;
	import org.splink.deepsplink.page.Page;
	import org.splink.library.distributor.Distributor;
	import org.splink.library.distributor.Dtype;
	import org.splink.library.distributor.IDevent;
	import org.splink.library.distributor.IDistributor;
	import org.splink.library.queue.QEvent;

	/**
	 * @author Max Kugland
	 */
	public class AsyncRequestPageStub extends Page implements IDistributor {
		private var _distributor : Distributor;
		private var _history : Array;
		private var _timer : Timer;

		public function AsyncRequestPageStub(supplier : IPageSupplier) {
			super(supplier);
			_distributor = new Distributor();
		}

		public function set history(history : Array) : void {
			_history = history;		
			var self : IDistributor = this;	
			setShowStrategy(new RequestShowStrategyStub(id, _history, true)).register(QEvent.COMPLETE, function(e : QEvent) : void {
				distribute(new AsyncRequestPageStubEvent(self, AsyncRequestPageStubEvent.SHOW));			});
			setHideStrategy(new RequestHideStrategyStub(id, _history, true)).register(QEvent.COMPLETE, function(e : QEvent) : void {
				distribute(new AsyncRequestPageStubEvent(self, AsyncRequestPageStubEvent.HIDE));
			});
		}

		override public function onParamsChanged(params : Array) : void {
			_history.push("params-" + id + "-" + params.length);
		}

		override public function initialize() : void {
			if(params.length > 0) _history.push("params-" + id + "-" + params.length);
			
			distribute(new AsyncRequestPageStubEvent(this, AsyncRequestPageStubEvent.INIT));
			_timer = new Timer(1, 1);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, function(e : TimerEvent) : void {
				_history.push("initialize-" + id);
				setInitialized();
			});
			_timer.start();
		}

		override public function finalize() : void {
			_timer.stop();
			_history.push("finalize-" + id);
			distribute(new AsyncRequestPageStubEvent(this, AsyncRequestPageStubEvent.FINALIZE));
			_distributor.finalize();
		}

		public function distribute(event : IDevent) : void {
			_distributor.distribute(event);
		}

		public function register(type : Dtype, fnc : Function, params : Object = null, priority : uint = 0.0) : IDistributor {
			return _distributor.register(type, fnc, params, priority);
		}

		public function unregister(type : Dtype, fnc : Function) : IDistributor {
			return _distributor.unregister(type, fnc);
		}
	}
}
